<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="rowDel">
                        <template slot="menu" slot-scope="{ row }">
                            <el-button
                                type="text"
                                icon="el-icon-view"
                                @click="viewGropuMember(row)"
                                >群组成员</el-button>
                        </template>
            </avue-crud>
            <el-dialog append-to-body title="群组成员" :visible.sync="modal1" v-if="modal1">
                <avue-crud
                    ref="crud"
                    :option="option"
                    v-model="form"
                    :page.sync="page1"
                    :table-loading="listLoading"
                    :before-open="handleOpenBefore"
                    :data="list"
                    :permission="permissionList1"
                    @on-load="getList1"
                    @search-change="searchChange1"
                    @refresh-change="refreshChange1"
                    @size-change="sizeChange1"
                    @current-change="currentChange1"
                    @row-update="update"
                    @row-save="create"
                    @row-del="rowDel1">
                    <template slot="menuLeft">
                        <el-button
                            class="filter-item"
                            type="primary"
                            size="small"
                            icon="el-icon-edit"
                            @click="addGropuMember">添加成员
                        </el-button>
                    </template>
                    <template
                        slot="username"
                        slot-scope="scope">
                        <span>{{ scope.row.username }}</span>
                    </template>
                    <template
                        slot="role"
                        slot-scope="scope">
                        <span
                            v-for="(role,index) in scope.row.roleList"
                            :key="index">
                            <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
                        </span>
                    </template>
                    <template
                        slot="deptId"
                        slot-scope="scope">
                        {{ scope.row.deptName }}
                        </template>
                        <template
                        slot="lockFlag"
                        slot-scope="scope">
                        <el-tag>{{ scope.label }}</el-tag>
                    </template>
                     <template
                        slot="post"
                        slot-scope="scope">
                        {{ getPostName(scope.row.post) }}
                    </template>
                </avue-crud>
            </el-dialog>
            <el-dialog append-to-body title="添加成员" :visible.sync="modal2" v-if="modal2"  width="93%" top="5vh" @close="close"  class="relate-member">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <div class="member-item">
                            <div class="member-label">组织机构</div>
                            <div class="member-content">
                                <avue-tree
                                    :option="treeOption"
                                    :data="treeData"
                                    @node-click="nodeClick">
                                    <span class="el-tree-node__label" slot-scope="{ node, data }">
                                    <el-tooltip class="item" effect="dark" content="无数据权限" placement="right-start" v-if="data.isLock">
                                        <span>{{node.label}}  <i class="el-icon-lock"></i></span>
                                    </el-tooltip>
                                    <span v-if="!data.isLock">{{node.label}}</span>
                                    </span>
                                </avue-tree>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="member-item">
                            <div class="member-label">选择人员</div>
                            <div class="member-content">
                                <div class="search-block">
                                    <a-input-search placeholder="请输入姓名" enter-button @search="onSearch" />
                                </div>
                                <a-table 
                                    row-key="userId"
                                    :columns="columns"
                                    :scroll="{ y: 'calc(90vh - 364px)' }"
                                    :data-source="allmemberList"
                                    :row-selection="{selectedRowKeys: selectedRowKeys, type: 'checkbox', onChange: selectMembers, onSelect: onSelect}"
                                    bordered
                                    :pagination="page2"
                                    :loading="loading"
                                    @change="handleTableChange"
                                >
                                <template slot="deptId" slot-scope="text,record">
                                    <span>
                                    {{ record.deptName }}
                                    </span>
                                </template>
                                <template slot="post" slot-scope="text,record">
                                    <span>
                                    {{ getPostName(record.post) }}
                                    </span>
                                </template>
                                </a-table>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="member-item">
                            <div class="member-label">已选中用户</div>
                            <div class="member-content">
                                <a-table 
                                    row-key="userId"
                                    :scroll="{ y: 'calc(90vh - 500px)' }"
                                    :columns="columns1"
                                    :data-source="chosememberList"
                                    bordered
                                >
                                    <span slot="action" slot-scope="text, record">
                                        <a @click="removeMember(record)">删除</a>
                                    </span>
                                </a-table>
                            </div>
                        </div>
                        <div class="btn-footer">
                            <el-button type="primary" @click="dataSubmit">确 定</el-button>
                            <el-button @click="close">取 消</el-button>
                        </div>
                    </el-col>
                </el-row>
                <!-- <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="dataSubmit">确 定</el-button>
                    <el-button @click="close">取 消</el-button>
                </div> -->
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
    import {fetchList, getObj, addObj, putObj, delObj, getUserPage, saveBatch, delUserObj} from '@/api/admin/sysgroup'
    import {addObj as addObj1, delObj as delObj1, fetchList as fetchList1, putObj as putObj1} from '@/api/admin/user'
    import {tableOption} from '@/const/crud/admin/sysgroup'
    import { fetchList as fetchList2 } from '@/api/admin/sysposition'
    import {tableOption as tableOption1} from '@/const/crud/admin/member'
    import {deptRoleList} from '@/api/admin/role'
    import {fetchTree} from '@/api/admin/dept'
    import {mapGetters} from 'vuex'

    export default {
        name: 'sysgroup',
        data() {
            return {
                pinyin: '',
                pagination: {},
                loading: false,
                columns:[
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '姓名',
                    key: 'realname',
                    dataIndex: 'realname',
                },
                {
                    title: '所属部门',
                    dataIndex: 'deptId',
                    key:'deptId',
                    scopedSlots: { customRender: 'deptId' },
                },
                {
                    title: '岗位',
                    dataIndex: 'post',
                    key: 'post',
                    scopedSlots: { customRender: 'post' }
                }
                ],
                treeOption: {
                    nodeKey: 'id',
                    addBtn: false,
                    defaultExpandAll:true,
                    menu: false,
                    props: {
                        label: 'name',
                        value: 'id'
                    }
                },
                columns1:[
                    {
                        title: '用户名',
                        dataIndex: 'username',
                        key: 'username' 
                    },
                    {
                        title: '操作',
                        key: 'action',
                        scopedSlots: { customRender: 'action' },
                    },
                ],
                chosememberList:[],
                treeData: [],
                option: tableOption1,
                treeDeptData: [],
                checkedKeys: [],
                page1: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条,
                    isAsc: false// 是否倒序
                },
                page2: {
                    total: 0, // 总页数
                    current: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条,
                    isAsc: false// 是否倒序
                },
                permissionList1:{
                    delBtn: true,
                },
                list: [],
                deptId: '',
                selectedRowKeys: [],
                allmemberList: [],
                listLoading: true,
                role: [],
                form: {},
                groupId: '',
                rolesOptions: [],
                searchForm: {},
                tableData: [],
                searchForm1: {},
                tableData1: [],
                modal1: false,
                modal2: false,
                modal3: false,
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permissions.admin_sysgroup_add, false),
                    delBtn: this.vaildData(this.permissions.admin_sysgroup_del, false),
                    editBtn: this.vaildData(this.permissions.admin_sysgroup_edit, false)
                };
            },
        },
        watch: {
            role() {
                this.form.role = this.role
            }
        },
        created() {
            this.init()
        },
        methods: {
            onSearch(val) {
                let att = {}
                att['realname'] = val
                if (this.pinyin) {
                    att['pinyin'] = this.pinyin
                } else {
                    att['pinyin'] = ''
                }
                this.page2.current = 1
                this.getmemberList(this.page2, att)
            },
            addGropuMember(row) {
                if (this.list.length) {
                    this.selectedRowKeys = []
                    this.list.map(item => {
                        this.selectedRowKeys.push(item.userId)
                    })
                    this.chosememberList = Object.assign([], this.list)
                }
                this.modal2 = true
                this.getmemberList(this.page2)
            },
            getPostName(id) {
                let list =  this.postList.filter(item => {
                    return item.id === id
                })
                return list.length > 0 ? list[0].name : ''
            },
            removeMember(record) {
                this.chosememberList = this.chosememberList.filter(item => {
                    return item.userId !== record.userId
                })
                let alist = []
                this.selectedRowKeys.map(item => {
                    if(item !== record.userId) {
                        alist.push(item)
                    }
                })
                this.selectedRowKeys = alist
            },
            viewGropuMember(row) {
                this.groupId = row.groupId
                this.modal1 = true
            },
            dataSubmit() {
                let params = {
                    groupId: this.groupId,
                    userIds:[]
                }
                if (this.chosememberList.length === 0) {
                    if (this.selectedRowKeys.length > 0) {
                        params.userIds = this.selectedRowKeys
                    } else {
                        params.userIds = []
                    }
                } else {
                    this.chosememberList.map(item => {
                        params.userIds.push(item.userId)
                    })
                }
                saveBatch(params).then(response => {
                     this.$message.success('添加成功')
                     this.close()
                     this.getList1(this.page1)
                })
            },
            close() {
                this.deptId = ''
                this.page2.current = 1
                this.selectedRowKeys = []
                this.chosememberList = []
                this.modal2 = false
            },
            selectMembers(selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys
            },
            onSelect(record, selected, selectedRows, nativeEvent) {
                if (selected) {
                    this.chosememberList.push(record)
                } else {
                    this.chosememberList = this.chosememberList.filter(item => {
                        return item.userId !== record.userId
                    })
                }
            },
            init() {
                fetchTree().then(response => {
                    this.treeData = response.data.data
                })
                fetchList2({current: 1, size:1000}).then(response => {
                    this.postList = response.data.data.records
                })
            },
            nodeClick(data) {
                this.page2.current = 1
                this.deptId = data.id
                this.getmemberList(this.page2, {deptId: data.id})
            },
            // 获取部门人员列表
            getmemberList(page, params) {
                fetchList1(Object.assign({
                    current: page.current,
                    size: page.pageSize
                }, params)).then(response => {
                    this.allmemberList = response.data.data.records
                    this.page2.total = response.data.data.total
                })
            },
            handleTableChange(pagination, filters, sorter) {
                this.page2.current = pagination.current
                this.getmemberList(this.page2, {deptId: this.deptId})
            },
            // 获取群组人员列表
            getList1(page, params) {
                this.listLoading = true
                getUserPage(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    groupId: this.groupId
                }, params, this.searchForm1)).then(response => {
                    this.list = response.data.data.records
                    this.page1.total = response.data.data.total
                    this.listLoading = false
                })
            },
            getNodeData() {
                deptRoleList().then(response => {
                    this.rolesOptions = response.data.data
                })
            },
            searchChange1(param, done) {
                this.searchForm1 = param
                this.page1.currentPage = 1
                this.getList1(this.page1, param)
                done()
            },
            sizeChange1(pageSize) {
                this.page1.pageSize = pageSize
            },
            currentChange1(current) {
                this.page1.currentPage = current
            },
            refreshChange1() {
                this.getList1(this.page1)
            },
            handleOpenBefore(show, type) {
                window.boxType = type
                // 查询部门树
                fetchTree().then(response => {
                    this.treeDeptData = response.data.data
                })
                // 查询角色列表
                deptRoleList().then(response => {
                    this.rolesOptions = response.data.data
                })

                if (['edit', 'views'].includes(type)) {
                    this.role = []
                    for (let i = 0; i < this.form.roleList.length; i++) {
                        this.role[i] = this.form.roleList[i].roleId
                    }
                } else if (type === 'add') {
                    this.role = []
                    this.form.username = undefined
                    this.form.phone = undefined
                    this.form.password = undefined
                }
                show()
            },
            create(row, done, loading) {
                if (this.form.phone && this.form.phone.indexOf('*') > 0) {
                this.form.phone = undefined
                }
                addObj1(this.form).then(() => {
                this.getList1(this.page)
                done()
                this.$notify.success('创建成功')
                }).catch(() => {
                loading()
                })
            },
            update(row, index, done, loading) {
                if (this.form.phone && this.form.phone.indexOf('*') > 0) {
                this.form.phone = undefined
                }
                putObj1(this.form).then(() => {
                this.getList1(this.page)
                done()
                this.$notify.success('修改成功')
                }).catch(() => {
                loading()
                })
            },
            rowDel1: function (row, index) {
                let self = this
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delUserObj({groupId: self.groupId, userId: row.userId})
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList1(this.page1)
                })
            },

            getList(page, params) {
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            rowDel: function (row, index) {
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.groupId)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            handleUpdate: function (row, index, done,loading) {
                putObj(row).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                addObj(row).then(data => {
                    this.$message.success('添加成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>
<style lang="scss">
    .relate-member{
        .el-dialog{
            height: 96%;
            .el-dialog__body{
                padding: 0 20px;
            }
        }
        .member-item{
            border:1px solid #e8e8e8;
            .member-label{
                height:40px;
                font-size: 15px;
                line-height: 40px;
                padding-left: 20px;
                border-bottom: 1px solid #e8e8e8;
            }
            .member-content{
                padding: 20px;
                padding-bottom: 0;
                .el-tree{
                    height: calc(90vh - 250px);
                    overflow: auto;
                }
                .search-block{
                    .ant-input{
                        width: 250px;
                        height: 32px;
                        font-size: 15px;
                    }
                    .ant-input-search{
                        margin-left: 10px;
                        width: 250px;
                        margin-bottom: 10px;
                        
                    }
                }
            }
        }
        .btn-footer{
            text-align: center;
            margin-top: 30px;
        }
    }
</style>